
package com.sailing.lianxi.io.nio;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.Pipe;

public class Test {

    
    public static void t3(){
        try {
            Pipe pipe = Pipe.open();
            Pipe.SinkChannel sinkChannel = pipe.sink();
            String data = "你好";
            ByteBuffer buf = ByteBuffer.allocate(48);
            buf.clear();
            buf.put(data.getBytes());
            buf.flip();
            while(buf.hasRemaining()){
                sinkChannel.write(buf);
            }
            Pipe.SourceChannel sourceChannel = pipe.source();
            int bytesRead = sourceChannel.read(buf);
            System.out.println("bytesRead="+bytesRead);
            
        } catch (Exception e) {
            
            // TODO Auto-generated catch block
            e.printStackTrace();
            
        }
        
    }
    
    
    public static void t1(){
     try {
        RandomAccessFile aFile = new RandomAccessFile("d:/lianxi/aim.txt", "rw");
        FileChannel inChannel = aFile.getChannel();
        String newData = "New String to write to file...";

        ByteBuffer buf = ByteBuffer.allocate(48);
        buf.clear();
        buf.put(newData.getBytes());
        buf.flip();

        while(buf.hasRemaining()) {
            inChannel.write(buf);
        }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
    
    
    private static void extracted() {
        try {
            RandomAccessFile fromFile = new RandomAccessFile("d:/lianxi/source.txt", "rw");
        FileChannel      fromChannel = fromFile.getChannel();

        RandomAccessFile toFile = new RandomAccessFile("d:/lianxi/aim.txt", "rw");
        FileChannel      toChannel = toFile.getChannel();
        long position = 0;
        long count = fromChannel.size();
        System.out.println(count);
        toChannel.transferFrom(fromChannel, position, count);
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        toChannel.write(buffer);
        byte b = buffer.get();
        System.out.println(b);
        System.out.println("文件传输成功");
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) {
        t3();
    }

   
}

